#!/usr/bin/env php
<?php
/*
 * load module command line script
 */


include_once (dirname(__FILE__)."/bin/app_init.php");
if(!defined("CLI")){
	exit;
}

//include_once dirname(__FILE__)."/require_auth.php";

include_once (MODULE_PATH."/system/lib/ModuleLoader.php");

$installSql = true;


$_moduleArr = glob(MODULE_PATH."/*");
$moduleArr[] = "system";
$moduleArr[] = "menu";
$moduleArr[] = "help";
$moduleArr[] = "contact";
$moduleArr[] = "cronjob";
foreach ($_moduleArr as $_module)
{
	$_module = basename($_module);
    if ($_module == "system" || 
	$_module == "menu" ||
	$_module == "help"||
	$_module == "contact"||
	$_module == "cronjob" 
	) continue;
    $moduleArr[] = $_module;	
}


foreach ($moduleArr as $moduleName)
{
	$loader = new ModuleLoader($moduleName);
	error_log( "Start loading $moduleName module ..."); 
	error_log( "--------------------------------------------------------");
	$loader->loadModule($installSql);
	error_log( $loader->errors . "");
	// give predefined users access to actions
	error_log( "Give admin to access all actions of module '$moduleName'");
	giveActionAccess("module='$moduleName'", 1);	// admin to access all actions
	error_log ("--------------------------------------------------------");
	error_log ("End loading $moduleName module");
	
}

$installLock = APP_FILE_PATH.DIRECTORY_SEPARATOR.'install.lock';
touch($installLock);
file_put_contents($installLock, '1');

// give predefined users access to actions
function giveActionAccess($where, $role_id)
{
	$db = BizSystem::dbConnection();
	try {
		if (empty($where))
			$sql = "SELECT * FROM acl_action";
		else
			$sql = "SELECT * FROM acl_action WHERE $where";
	    BizSystem::log(LOG_DEBUG, "DATAOBJ", $sql);
	    $rs = $db->fetchAll($sql);
	    
	    $sql = "";
		foreach ($rs as $r) {
			$sql = "DELETE FROM acl_role_action WHERE role_id=$role_id AND action_id=$r[0]; ";
			BizSystem::log(LOG_DEBUG, "DATAOBJ", $sql);
			$db->query($sql);
			$sql = "INSERT INTO acl_role_action (role_id, action_id, access_level) VALUES ($role_id,$r[0],1)";
			BizSystem::log(LOG_DEBUG, "DATAOBJ", $sql);
	    	$db->query($sql);
		}
	}
	catch (Exception $e) {
	    echo "ERROR: ".$e->getMessage()."".PHP_EOL;
	    return false;
	}
}
?>
